package com.qys.livesMall.system.source.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qys.livesMall.cache.RedisCache;
import com.qys.livesMall.cache.utils.CacheUtil;
import com.qys.livesMall.common.enums.LanguageEnum;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.common.utils.QysStringUtils;
import com.qys.livesMall.common.utils.bean.BeanProUtils;
import com.qys.livesMall.framework.view.QysPage;
import com.qys.livesMall.system.constants.Constants;
import com.qys.livesMall.system.source.domain.dto.dict.AddDictType;
import com.qys.livesMall.system.source.domain.dto.dict.DictDataSearch;
import com.qys.livesMall.system.source.domain.dto.dict.DictTypeSearch;
import com.qys.livesMall.system.source.domain.dto.dict.EditDictType;
import com.qys.livesMall.system.source.domain.entity.SysDictData;
import com.qys.livesMall.system.source.domain.entity.SysDictType;
import com.qys.livesMall.system.source.domain.vo.dict.DictTypeVO;
import com.qys.livesMall.system.source.domain.vo.dict.DictVO;
import com.qys.livesMall.system.source.mapper.SysDictDataMapper;
import com.qys.livesMall.system.source.mapper.SysDictTypeMapper;
import com.qys.livesMall.system.source.service.ISysDictTypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 字典 业务层处理
 *
 * @author wanglei
 */
@Service
public class SysDictTypeServiceImpl implements ISysDictTypeService {
    @Autowired
    private SysDictTypeMapper dictTypeMapper;

    @Autowired
    private SysDictDataMapper dictDataMapper;

    @Autowired
    private RedisCache redisCache;

    /**
     * 项目启动时，初始化字典到缓存
     */
//    @PostConstruct
//    public void init() {
//        loadingDictCache();
//    }

    /**
     * 根据条件分页查询字典类型
     *
     * @param search 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public QysPage<DictTypeVO> selectDictTypeList(DictTypeSearch search) {
        Page<SysDictType> sPage = dictTypeMapper.selectDictTypeList(new Page<>(search.getPageNum(), search.getPageSize()), search);
        return QysPage.to(sPage, DictTypeVO.class);
    }

    /**
     * 根据所有字典类型
     *
     * @return 字典类型集合信息
     */
    @Override
    public List<DictTypeVO> selectDictTypeAll() {
        List<SysDictType> types = dictTypeMapper.selectDictTypeAll();
        return BeanProUtils.copyListProperties(types, DictTypeVO::new);
    }

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<DictVO> selectDictDataByType(String dictType, String languageType) {
        String key = CacheUtil.getKey(Constants.SysRedisKeyPrefix.DICT, languageType+":"+dictType);
        List<DictVO> dictDatas = redisCache.getCacheObject(key);
        if (QysStringUtils.isNotEmpty(dictDatas)) {
            return dictDatas;
        }
        List<SysDictData> dictData = dictDataMapper.selectDictDataByType(dictType,languageType);
        if (QysStringUtils.isNotEmpty(dictData)) {
            dictDatas=BeanProUtils.copyListProperties(dictData,DictVO::new);
            redisCache.setCacheObject(key, dictDatas);
            return dictDatas;
        }else {
            dictData = dictDataMapper.selectDictDataByType(dictType,LanguageEnum.EN_US.getLang());
            if (QysStringUtils.isEmpty(dictData)) {
                return null;
            }
            dictDatas=BeanProUtils.copyListProperties(dictData,DictVO::new);
            redisCache.setCacheObject(key, dictDatas);
            return dictDatas;
        }
    }

    /**
     * 根据字典类型ID查询信息
     *
     * @param dictId 字典类型ID
     * @return 字典类型
     */
    @Override
    public DictTypeVO selectDictTypeById(Long dictId) {

        SysDictType type = dictTypeMapper.selectDictTypeById(dictId);
        if (type == null) {
            return null;
        }
        DictTypeVO vo = new DictTypeVO();
        BeanUtils.copyProperties(type, vo);
        return vo;
    }

    /**
     * 根据字典类型查询信息
     *
     * @param dictType 字典类型
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeByType(String dictType) {
        return dictTypeMapper.selectDictTypeByType(dictType);
    }

    /**
     * 批量删除字典类型信息
     *
     * @param dictIds 需要删除的字典ID
     */
    @Override
    public void deleteDictTypeByIds(Long[] dictIds) {
        for (Long dictId : dictIds) {
            SysDictType dictType = dictTypeMapper.selectDictTypeById(dictId);
            if (dictDataMapper.countDictDataByType(dictType.getDictType()) > 0) {
                throw new QysException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
            dictTypeMapper.deleteDictTypeById(dictId);
            String key = CacheUtil.getKey(Constants.SysRedisKeyPrefix.DICT, dictType.getDictType());
            redisCache.deleteObject(key);
        }
    }

    /**
     * 加载字典缓存数据
     */
    @Override
    public void loadingDictCache() {
        DictDataSearch dictData = new DictDataSearch();
        dictData.setStatus("0");
        Map<String, List<SysDictData>> dictDataMap = dictDataMapper.selectDictDataList(null, dictData).getRecords().stream().collect(Collectors.groupingBy(SysDictData::getDictType));
        for (Map.Entry<String, List<SysDictData>> entry : dictDataMap.entrySet()) {
            String key = CacheUtil.getKey(Constants.SysRedisKeyPrefix.DICT, entry.getKey());
            List<DictVO> dictVOS=BeanProUtils.copyListProperties(dictDataMap.get(key),DictVO::new);
            redisCache.setCacheObject(key,dictVOS);
        }
    }

    /**
     * 清空字典缓存数据
     */
    @Override
    public void clearDictCache() {
        redisCache.deleteObject(CacheUtil.getKey(Constants.SysRedisKeyPrefix.DICT, "*"));
    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache() {
        clearDictCache();
        loadingDictCache();
    }

    /**
     * 新增保存字典类型信息
     *
     * @param dictType 字典类型信息
     * @return 结果
     */
    @Override
    public R insertDictType(AddDictType dictType) {
        if (checkDictTypeExist(dictType.getDictType())) {
            return R.fail("新增字典'" + dictType.getDictName() + "'失败，字典类型已存在");
        }
        SysDictType type = new SysDictType();
        BeanUtils.copyProperties(dictType, type);
        int row = dictTypeMapper.insertDictType(type);
        return R.ok();
    }

    /**
     * 修改保存字典类型信息
     *
     * @param dictType 字典类型信息
     * @return 结果
     */
    @Override
    public R updateDictType(EditDictType dictType) {

        SysDictType oldDict = dictTypeMapper.selectDictTypeById(dictType.getDictId());
        BeanUtils.copyProperties(dictType, oldDict);
        int row = dictTypeMapper.updateDictType(oldDict);
        return R.ok();
    }

    /**
     * 校验字典类型称是否唯一
     *
     * @param dictType 字典类型
     * @return 结果
     */
    @Override
    public boolean checkDictTypeExist(String dictType) {
        SysDictType type = dictTypeMapper.selectDictTypeByType(dictType);
        return type != null;
    }




}
